// 能不能根据环境来动态设置BASE_URL呢？

const BASE_URL = 'https://server.alevel.ciyufish.cn/api'
// const BASE_URL = 'http://192.168.124.14:8848'

// 普通请求
export const request = options => {
	return new Promise((resolve, reject) => {
		uni.request({
			url: BASE_URL + options.url,
			method: options.method || 'GET',
			data: options.data,
			timeout: 30000,
			header: {
				'content-type': 'application/json',
				...options.header
			},
			enableHttp2: true, // 开启 HTTP2
			enableQuic: true, // 开启 QUIC
			success: res => {
				if (res.statusCode === 200) {
					resolve(res.data)
				} else {
					reject(res)
				}
			},
			fail: err => {
				reject(err)
			}
		})
	})
}

// 文件上传请求
export const uploadFile = options => {
	return new Promise((resolve, reject) => {
		const uploadTask = uni.uploadFile({
			url: BASE_URL + options.url,
			filePath: options.filePath,
			name: 'avatar', // 与后端接收的字段名保持一致
			formData: {}, // 如果需要额外的表单数据
			success: uploadFileRes => {
				if (uploadFileRes.statusCode === 200) {
					try {
						const result = JSON.parse(uploadFileRes.data)
						resolve(result)
					} catch (error) {
						reject(new Error('解析响应失败'))
					}
				} else {
					reject(new Error('上传失败: ' + uploadFileRes.statusCode))
				}
			},
			fail: err => {
				console.error('上传错误:', err)
				reject(err)
			}
		})

		// 监听上传进度
		uploadTask.onProgressUpdate(res => {
			console.log('上传进度:', res.progress)
		})
	})
}
